using System;
using System.Management;
//using System.Management.EventWatching;
class Win_serialPort
{
    static void Win_serialPort1(string[] args)
    {
        // 创建 WqlEventQuery 对象，用于查询 WMI 事件
        WqlEventQuery query = new WqlEventQuery("SELECT * FROM __InstanceOperationEvent WITHIN 1 WHERE TargetInstance ISA 'Win32_PnPEntity'");
 
        // 创建 ManagementEventWatcher 对象，用于订阅事件
        ManagementEventWatcher watcher = new ManagementEventWatcher(query);
 
        // 订阅事件处理程序
        watcher.EventArrived += new EventArrivedEventHandler(PnpEntityEventArrived);
 
        // 开始监听事件
        watcher.Start();
 
        Console.WriteLine("Monitoring PNP events. Press Enter to exit.");
        Console.ReadLine();
 
        // 停止监听事件
        watcher.Stop();
    }
 
    private static void PnpEntityEventArrived(object sender, EventArrivedEventArgs e)
    {
        // 处理事件，区分添加和移除事件
        string eventType = e.NewEvent.Properties["EventType"].Value.ToString();
        string deviceName = e.NewEvent.Properties["TargetInstance.Name"].Value.ToString();
 
        if (eventType == "1") // 1 表示添加事件
        {
            Console.WriteLine($"Device added: {deviceName}");
        }
        else if (eventType == "2") // 2 表示移除事件
        {
            Console.WriteLine($"Device removed: {deviceName}");
        }
    }
}